/**
 * 
 */
package com.alstudio.event;

/**
 * @author alonso lee
 *
 */
final class PendingALEventQueue {
    private PendingALEvent head;
    private PendingALEvent tail;

    synchronized void enqueue(PendingALEvent pendingAlEvent) {
        if (pendingAlEvent == null) {
            throw new NullPointerException("null cannot be enqueued");
        }
        if (tail != null) {
            tail.next = pendingAlEvent;
            tail = pendingAlEvent;
        } else if (head == null) {
            head = tail = pendingAlEvent;
        } else {
            throw new IllegalStateException("Head present, but no tail");
        }
        notifyAll();
    }

    synchronized PendingALEvent poll() {
        PendingALEvent pendingAlEvent = head;
        if (head != null) {
            head = head.next;
            if (head == null) {
                tail = null;
            }
        }
        return pendingAlEvent;
    }

    synchronized PendingALEvent poll(int maxMillisToWait) throws InterruptedException {
        if (head == null) {
            wait(maxMillisToWait);
        }
        return poll();
    }
}
